package com.taotao.credentialsmatcher;
import java.util.concurrent.atomic.AtomicInteger;
 
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache; 
import org.apache.shiro.cache.CacheManager;
import org.springframework.util.DigestUtils;
 
/** 
 * 自定义 密码验证类 
 * 
 * @author q 
 * 
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {  
	
	//private Ehcache passwordRetryCache;
	private Cache<String,AtomicInteger> passwordRetryCache;
	
	public CustomCredentialsMatcher(CacheManager cacheManager) {
 
		 passwordRetryCache = cacheManager.getCache("passwordRetryCache");  
    }
	
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
    	
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String loginName = token.getUsername();
		String password = String.valueOf(token.getPassword());
		
		String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
		AtomicInteger retryCount = passwordRetryCache.get(loginName);
		if(retryCount==null){
			retryCount = new AtomicInteger();
			passwordRetryCache.put(loginName, retryCount);
		}
		if(retryCount.incrementAndGet()>5){
			 System.out.println("已经超过登录次数（5次）");
		     throw new ExcessiveAttemptsException();
		}
		
		//假设的一个验证机制
        int resp;
		try {
			resp = Integer.parseInt(pwd);
		} catch (Exception e) {
			resp = 0;
		}
		if(resp == 1){
			//clear retry count
			passwordRetryCache.remove(loginName);
            return true;
		}else{
			return false;
		}
		
    }
 
	public Cache<String, AtomicInteger> getPasswordRetryCache() {
		return passwordRetryCache;
	}
 
	public void setPasswordRetryCache(Cache<String, AtomicInteger> passwordRetryCache) {
		this.passwordRetryCache = passwordRetryCache;
	}
    
}